package com.sjyl.kaoshitong.witget;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.View;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.sjyl.kaoshitong.R;
import com.sjyl.kaoshitong.beans.CatalogItem;
import com.sjyl.kaoshitong.util.PreferencesKeyUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by ChangerLow on 15/6/30.
 * Email: changerlow@qq.com
 */
public class FilterBranchSelectorDialog extends DialogFragment implements MaterialDialog.ListCallback {
    private static String TAG = "FilterBranchSelectorDialog";
    private boolean canGoUp = false;
    private MaterialDialog dialog;
    private BranchSelectCallback mCallback;

    private Map<Integer, List<String>> catalogLevelMap;
    private Map<String, CatalogItem> catalogItemMap;
    private int currentLevel = 1;
    private int maxLevel = 0;
    private List<String> currentidsList;
    private String title = "选择分支";
    private String currentId = "";
    private LinkedList<String> selectedName;
    private LinkedList<String> selectedId;
    private boolean showPositiveAction = false;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Hawk.init(getActivity());
        catalogLevelMap = new HashMap<Integer, List<String>>();
        catalogItemMap = new HashMap<String, CatalogItem>();
        List<CatalogItem> list = Hawk.get("catalog_list");
        maxLevel = processCatalogList(list);
        selectedId = new LinkedList<String>();
        selectedName = new LinkedList<String>();
    }

    private final MaterialDialog.ButtonCallback mButtonCallback = new MaterialDialog.ButtonCallback() {
        @Override
        public void onPositive(MaterialDialog materialDialog) {
            materialDialog.dismiss();
            Hawk.put(PreferencesKeyUtil.KEY_CURRENT_LEVEL, currentLevel);
            Hawk.put(PreferencesKeyUtil.KEY_CURRENT_SELECTED_ID, selectedId.getLast());
            Hawk.put(PreferencesKeyUtil.KEY_FILTER_SELECTED_PATH, selectedName);
            mCallback.onBranchSelection(selectedId);
        }

        @Override
        public void onNegative(MaterialDialog materialDialog) {
            materialDialog.dismiss();
        }
    };

    public interface BranchSelectCallback {
        void onBranchSelection(List<String> ids);
    }

    public static FilterBranchSelectorDialog newInstance(String arg) {
        FilterBranchSelectorDialog dialog = new FilterBranchSelectorDialog();
        Bundle bundle = new Bundle();
        dialog.setArguments(bundle);
        return dialog;
    }

    public FilterBranchSelectorDialog() {
    }

    String[] getContentsArray(String id, boolean goUp) {
        if (currentLevel > 1) {
            canGoUp = true;
        } else {
            canGoUp = false;
        }
        List<String> idList = catalogLevelMap.get(currentLevel);
        List<String> results = new ArrayList<String>();
        currentidsList = new ArrayList<String>();
        if (canGoUp) {
            results.add(getActivity().getString(R.string.filter_dialog_back_up));
            currentidsList.add("first_level");
        }

        //if goUP==true， add id's(id=goUP_id when goup id come from selectedId's last item) pid ;
        //else add id's(item id) son id;
        for (int i = 0; i < idList.size(); i++) {
            CatalogItem item = catalogItemMap.get(idList.get(i));
            String catalogName = item.getCatalog_name();
            String catalogId = item.getId();

            if(isLeaf(catalogId)){
                showPositiveAction = true;
                continue;
            }

            if (goUp) {
                if (!id.equals("")) {
                    String pid = catalogItemMap.get(id).getPid();
                    if (item.getPid().equals(pid)){
                        results.add(catalogName);
                        Logger.i(TAG, "special  gen list goup------equal pid " + id + " self id " + catalogId + " self pid " + item.getPid());
                        currentidsList.add(catalogId);
                    }
                } else {
                        results.add(catalogName);
                        Logger.i(TAG, "gen list goup------equal pid " + id + " self id " + catalogId + " self pid " + item.getPid());
                        currentidsList.add(catalogId);
                }
            } else {
                if (item.getPid().equals(id) && !isLeaf(item.getId())) {
                    Logger.i(TAG, "gen list not goup------equal pid " + id + " self id " + catalogId + " self pid " + item.getPid());
                    results.add(catalogName);
                    currentidsList.add(catalogId);
                }
            }
        }
        Logger.d(TAG, "result array in getContentArray is " + results.size());
        String[] arrayResult = new String[results.size()];
        results.toArray(arrayResult);
        return arrayResult;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        dialog = new MaterialDialog.Builder(getActivity())
                .title(getActivity().getString(R.string.filter_dialog_title))
                .items(getContentsArray("", true))
                .itemsCallback(this)
                .callback(mButtonCallback)
                .autoDismiss(false)
                .positiveText(android.R.string.ok)
                .negativeText(android.R.string.cancel)
                .build();
        dialog.getActionButton(DialogAction.POSITIVE).setVisibility(View.GONE);
        return dialog;
    }

    @Override
    public void onSelection(MaterialDialog dialog, View view, int i, CharSequence s) {
        Logger.d(TAG, "***************onSelection");
        //if has son and not has grandson, stop show next level!
        //if has son and grandson , show next level!
        boolean goUP = false;
        if (canGoUp && i == 0) {
            goUP = true;
            currentLevel = currentLevel - 1;
            currentId = selectedId.getLast();
            selectedId.removeLast();
            selectedName.removeLast();
        } else {
            goUP = false;
            currentLevel = currentLevel + 1;
            currentId = currentidsList.get(i);
            canGoUp = true;
            selectedId.add(currentId);
            selectedName.add(s.toString());
        }
        Logger.d(TAG, "======currentLevel " + currentLevel + "  current name " + s + "   currentid " + currentId);
        if (currentLevel == 1) {
            dialog.setTitle(title);
        } else {
            String title = TextUtils.join("/", selectedName);
            String ids = TextUtils.join("  ", selectedId);
            Logger.d(TAG, "********** selectedName " + title + "    selectedIds " + ids);
            dialog.setTitle(title);
        }

        showPositiveAction = false;

        String[] result = getContentsArray(currentId, goUP);

        if (currentLevel <=maxLevel && result.length > 1) {
            dialog.setItems(result);
            if(!showPositiveAction) {
                dialog.getActionButton(DialogAction.POSITIVE).setVisibility(View.GONE);
            }else {
                dialog.getActionButton(DialogAction.POSITIVE).setVisibility(View.VISIBLE);
            }
        } else if (result.length == 1) {
            dialog.setItems(result);
            dialog.setSelectedIndex(i);
            dialog.getActionButton(DialogAction.POSITIVE).setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mCallback = (BranchSelectCallback) getTargetFragment();

    }

    private int processCatalogList(List<CatalogItem> list) {
        if (list.size() == 0)
            return 0;
        int maxLevel = 0;
        catalogLevelMap.clear();
        catalogItemMap.clear();
        Logger.d(TAG, "catalog list size is " + list.size());
        for (int i = 0; i < list.size(); i++) {
            CatalogItem catalogItem = list.get(i);
            int catalog_level = catalogItem.getCatalog_level();
            Logger.d(TAG, "Processing catalog level is " + catalog_level);
            String id = catalogItem.getId();
            if (catalog_level > maxLevel) {
                maxLevel = catalog_level;
            }
            catalogItemMap.put(id, catalogItem);

            if (catalogLevelMap.containsKey(catalog_level)) {
                catalogLevelMap.get(catalog_level).add(catalogItem.getId());
            } else {
                List<String> catalog_level_list = new ArrayList<String>();
                catalog_level_list.add(catalogItem.getId());
                catalogLevelMap.put(catalog_level, catalog_level_list);
            }
        }

        Logger.d(TAG, " catalogitemmap size is " + catalogItemMap.keySet().size());
        Logger.d(TAG, " the max level is " + maxLevel + " catalogLevelMap size " + catalogLevelMap.keySet().size());
        return maxLevel;
    }

    private boolean isValidLastDir(String id) {
        Logger.i(TAG, "======isValidLastDir " + id);
        boolean hasChild = false;
        boolean hasGrandChild = false;
        String childId = "";
        CatalogItem item = catalogItemMap.get(id);
        int nextLevel = item.getCatalog_level() + 1;
        if (nextLevel <= maxLevel) {
            List<String> catalogList = catalogLevelMap.get(nextLevel);
            for (int i = 0; i < catalogList.size(); i++) {
                CatalogItem childItem = catalogItemMap.get(catalogList.get(i));
                if (childItem.getPid().equals(id)) {
                    hasChild = true;
                    childId = childItem.getId();
                    break;
                } else {
                    childId = childItem.getId();
                    hasChild = false;
                }
            }
            if (nextLevel == maxLevel || hasChild) {
                return true;
            }
            List<String> catalogListLast = catalogLevelMap.get(nextLevel + 1);
            for (int i = 0; i < catalogListLast.size(); i++) {
                CatalogItem childItem = catalogItemMap.get(catalogListLast.get(i));
                if (childItem.getPid().equals(childId)) {
                    hasGrandChild = true;
                    break;
                } else {
                    hasGrandChild = false;
                }

            }
        }
        if (hasChild && !hasGrandChild)
            return true;
        else
            return false;
    }


    private boolean isLeaf(String id){
        boolean hasChild = false;
        CatalogItem item = catalogItemMap.get(id);
        int nextLevel = item.getCatalog_level() + 1;
        if (nextLevel <= maxLevel) {
            List<String> catalogList = catalogLevelMap.get(nextLevel);
            for (int i = 0; i < catalogList.size() && !hasChild; i++) {
                CatalogItem childItem = catalogItemMap.get(catalogList.get(i));
                if (childItem.getPid().equals(id)) {
                    hasChild = true;
                    break;
                } else {
                    hasChild = false;
                }
            }
        }
        Logger.i(TAG, "========= id "+item.getCatalog_name() +" is Leaf "+hasChild);
        return !hasChild;
    }




    private static class FolderSorter implements Comparator<File> {
        @Override
        public int compare(File lhs, File rhs) {
            return lhs.getName().compareTo(rhs.getName());
        }
    }
}
